package com.kgc.onlineLife.service.impl;

import com.kgc.onlineLife.bean.Category;
import com.kgc.onlineLife.mapper.CategoryMapper;
import com.kgc.onlineLife.service.CategoryService;
import com.kgc.onlineLife.service.ProductService;
import com.kgc.onlineLife.util.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created On : 2022/4/15.
 * <p>
 * Author     : 张冲
 * <p>
 * Description: CategoryService
 */
@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private ProductService productService;

    @Override
    public List<Category> categoryList() {

        return  categoryMapper.selectCategoryList();
    }

    @Override
    public Category selectCategoryByCid(Integer cid) {
        return categoryMapper.selectCategory(cid);
    }

    @Override
    public List<Category> queryCategories(Page page) {
        List<Category> categories = categoryMapper.selectCategoriesPage(page);
        for (Category cate : categories){
            cate.setOnlineStatusProduct(productService.queryOnlineProductByCid(cate.getId()));
        }

        return categories;
    }

    @Override
    public List<Category> queryCategoriesByName(String name) {
        return categoryMapper.selectCategoriesByName(name);
    }

    @Override
    public boolean removeCategory(Integer id) {
        return categoryMapper.deleteCategory(id) > 0;
    }

    @Override
    public boolean addCategory(String cname) {
        // 新增前判断是否存在相同分类
        if (categoryMapper.selectCategoryByName(cname).size() != 0){
            System.out.println("存在相同分类名称");
            return false;
        }
        return categoryMapper.insertCategory(cname) > 0;
    }

    @Override
    public Category queryCategoryById(Integer cid) {
        return categoryMapper.selectCategoryById(cid);
    }

    @Override
    public boolean modCategoryById(Integer cid, String cname) {
        // 修改前判断商品名是否存在
        if (categoryMapper.selectCategoryByName(cname).size() != 0 && !(categoryMapper.selectCategoryByName(cname).get(0).getId() == cid)){
            System.out.println("存在相同分类名称");
            return false;
        }
        return categoryMapper.updateCategoryById(cid, cname) > 0;
    }

    @Override
    public List<Category> queryCategoriesNoPage() {
        return categoryMapper.selectCategoriesNoPage();
    }
}
